package abstractions;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import server.rmiServer;

public class rmiClient{
	/**
	 * Create the frame.
	 */
    
    public static final File SERIALIZED_STUB_FILE = new File("C:\\Users\\Tamara\\workspace2\\compute-stubs.bin");
	public static final String POLICY_FILE_NAME = "allow_all.policy";
	   
	//engine is the class the object that implements Service Services
	public ServerServices rmiClientHandler(Class<?> clazzToAddToServerCodebase, String ip){
		
        System.setProperty("java.rmi.server.codebase", clazzToAddToServerCodebase
                .getProtectionDomain().getCodeSource().getLocation().toString());

        System.setProperty("java.security.policy", getLocationOfPolicyFile());
        
        System.setProperty("java.rmi.server.hostname", ip);

        if(System.getSecurityManager() == null) {
        	System.setSecurityManager(new SecurityManager());
        }
    	   	
        try {
           ObjectInputStream in = new ObjectInputStream(new FileInputStream(SERIALIZED_STUB_FILE));
           return (ServerServices) in.readObject();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
		return null;
    }
        
	    public static String getLocationOfPolicyFile() {
	        try {
	            File tempFile = File.createTempFile("rmi-base", ".policy");
	            InputStream is = rmiServer.class.getResourceAsStream(POLICY_FILE_NAME);
	            BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
	            int read = 0;
	            while((read = is.read()) != -1) {
	                writer.write(read);
	            }
	            writer.close();
	            tempFile.deleteOnExit();
	            return tempFile.getAbsolutePath();
	        }
	        catch(IOException e) {
	            throw new RuntimeException(e);
	        }
	    }        

}
